﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;

namespace iMall.Biz.Attributes
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class DateAttribute : ValidationAttribute
    {
        private DateTime minDate;
        private DateTime maxDate;
        private bool isFormatError = true;

        public DateAttribute ( )
        {
            MinDate = new DateTime(1753, 1, 1).ToString();
            MaxDate = new DateTime(9999, 12, 31).ToString();
        }

        public string MinDate { get; set; }

        public string MaxDate { get; set; }


        public override bool IsValid ( object value )
        {
            if ( value == null || string.IsNullOrEmpty(value.ToString()) )
            { return true; }

            string s = value.ToString();
            minDate = DateTime.Parse(MinDate);
            maxDate = DateTime.Parse(MaxDate);

            bool result = true;
            try
            {
                DateTime date = DateTime.Parse(s);
                isFormatError = false;
                if ( date > maxDate || date < minDate )
                {
                    result = false;
                }
            }
            catch ( Exception )
            {
                result = false;
            }

            return result;
        }

        public override string FormatErrorMessage ( string name )
        {
            if ( isFormatError )
            { return "请输入合法的日期"; }

            return base.FormatErrorMessage(name);
        }
    }
}
